package com.jss.lanouhn.fristapp.fragments.homeChirdFragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jss.lanouhn.fristapp.Interface.OnItemClickLister;
import com.jss.lanouhn.fristapp.R;
import com.jss.lanouhn.fristapp.activity.HomeSelectSmallFreeActivity;
import com.jss.lanouhn.fristapp.activity.HomeSelectSmallLastActivity;
import com.jss.lanouhn.fristapp.activity.HomeSelectSmallNormalActivity;
import com.jss.lanouhn.fristapp.activity.LBTWebViewActivity;
import com.jss.lanouhn.fristapp.activity.SuperActivity;
import com.jss.lanouhn.fristapp.adapters.HomeBigAdapter;
import com.jss.lanouhn.fristapp.adapters.HomeSmallAdapter;
import com.jss.lanouhn.fristapp.custom.MyRecyclerView;
import com.jss.lanouhn.fristapp.modles.homeModles.BelowLunBoTu;
import com.jss.lanouhn.fristapp.modles.homeModles.HomeRecyclerView;
import com.jss.lanouhn.fristapp.modles.homeModles.LunBoTu;
import com.jss.lanouhn.fristapp.view.ImageCycleView;
import com.squareup.picasso.Picasso;
import com.ybao.pullrefreshview.layout.BaseFooterView;
import com.ybao.pullrefreshview.layout.BaseHeaderView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by lanouhn on 16/8/24.
 */
public class Home_chose_fragment extends Fragment implements BaseHeaderView.OnRefreshListener, BaseFooterView.OnLoadListener {
    private BaseHeaderView headerView;
    private BaseFooterView footerView;

    private ImageCycleView rollPagerView;
    private RecyclerView recyclerViewSmall;
    private MyRecyclerView recyclerView;
    private LunBoTu lunBoTu;
    private BelowLunBoTu belowLunBoTu;
    private HomeSmallAdapter adapter_small;
    private HomeBigAdapter homeBigAdapter;
    private String url = "http://api.liwushuo.com/v2/banners?channel=iOS";
    private String url1 = "http://api.liwushuo.com/v2/secondary_banners?gender=1&generation=2";
    private String url2 = "http://api.liwushuo.com/v2/channels/101/items_v2?ad=2&gender=1&generation=2&limit=20&offset=";

    private List<HomeRecyclerView.DataBean.ItemsBean> listRecyview = new ArrayList<>();
    private List<HomeRecyclerView.DataBean.ItemsBean> tempListRecyview = new ArrayList<>();


    private int offset = 0;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.home_chose_fragment, null);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        headerView = (BaseHeaderView) getView().findViewById(R.id.header);
        footerView = (BaseFooterView) getView().findViewById(R.id.footer);
        rollPagerView = (ImageCycleView) getView().findViewById(R.id.rpv_home);
        recyclerViewSmall = (RecyclerView) getView().findViewById(R.id.rv_home_small);
        recyclerView = (MyRecyclerView) getView().findViewById(R.id.rv_home_big);

        LinearLayoutManager manager1 = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(manager1);

        headerView.setOnRefreshListener(this);
        footerView.setOnLoadListener(this);
        initDataWeb();//加载轮播图数据
        initDataSmall();//加载轮播图下面的水平滑动的图片
        initData();//加载recyclerView数据
    }

    private void initDataWeb() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(url)
                        .build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        Gson gson = new Gson();
                        lunBoTu = gson.fromJson(result, LunBoTu.class);
                        if (lunBoTu.getData().getBanners().size() > 0) {
                            handler.sendEmptyMessage(1);
                        } else {
                            Toast.makeText(getActivity(), "没有数据", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }).start();
    }

    private void initData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(url2 + offset)
                        .build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        handler.sendEmptyMessage(4);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        Gson gson = new Gson();

                        HomeRecyclerView homeRecyclerView = gson.fromJson(result, HomeRecyclerView.class);

                        int code = homeRecyclerView.getCode();
                        if(code==200){
                            tempListRecyview = homeRecyclerView.getData().getItems();
                            if (tempListRecyview.size() > 0) {
                                handler.sendEmptyMessage(3);
                            } else {
                                handler.sendEmptyMessage(5);
                            }
                        }else{
                            handler.sendEmptyMessage(4);
                        }
                    }
                });
            }
        }).start();
    }

    //加载轮播图下面的水平滑动的图片
    private void initDataSmall() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(url1)
                        .build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        Gson gson = new Gson();
                        belowLunBoTu = gson.fromJson(result, BelowLunBoTu.class);
                        if (belowLunBoTu.getData().getSecondary_banners().size() > 0) {
                            handler.sendEmptyMessage(2);
                        } else {
                            Toast.makeText(getActivity(), "没有数据", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }).start();
    }

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);


            switch (msg.what) {
                case 1:
                    //设置轮播图适配器
                    List<String> adUrls = new ArrayList<>();
                    final List<LunBoTu.DataBean.BannersBean> beans = lunBoTu.getData().getBanners();
                    for (LunBoTu.DataBean.BannersBean b : beans) {
                        adUrls.add(b.getImage_url());
                    }
                    rollPagerView.setImageResources(adUrls, new ImageCycleView.ImageCycleViewListener() {
                        @Override
                        public void displayImage(String imageURL, ImageView imageView) {
                            Picasso.with(getActivity()).load(imageURL).into(imageView);
                        }

                            @Override
                            public void onImageClick(int position, View imageView) {

                                LunBoTu.DataBean.BannersBean bean = beans.get(position);

                                switch (bean.getType()) {
                                    case "collection":
                                        Intent intent = new Intent(getActivity(), SuperActivity.class);
                                        Bundle bundle = new Bundle();
                                        bundle.putInt("id", bean.getTarget_id());
                                        intent.putExtras(bundle);
                                        getActivity().startActivity(intent);
                                        break;
                                    case "post":
                                        Intent intent1 = new Intent(getActivity(), LBTWebViewActivity.class);
                                        Bundle bundle1 = new Bundle();
                                        bundle1.putInt("longId", bean.getTarget_id());
                                        intent1.putExtras(bundle1);
                                        getActivity().startActivity(intent1);
                                        break;
                                    case "url":

                                        break;
                                }
                            }
                        });

                case 2:
                    //给轮播图下面的小图加载数据
                    LinearLayoutManager manager = new LinearLayoutManager(getActivity());
                    manager.setOrientation(LinearLayoutManager.HORIZONTAL);
                    recyclerViewSmall.setLayoutManager(manager);
                    adapter_small = new HomeSmallAdapter(getActivity(), belowLunBoTu);
                    adapter_small.setOnItemClickLister(new OnItemClickLister() {
                        @Override
                        public void onItemClick(View view, final int position) {
                            BelowLunBoTu.DataBean.SecondaryBannersBean bean =
                                    belowLunBoTu.getData().getSecondary_banners().get(position);
                            String id = bean.getTarget_url().substring(bean.getTarget_url().length() - 3);

                            if (position == 0) {
                                Intent intent = new Intent(getActivity(), HomeSelectSmallFreeActivity.class);
                                getActivity().startActivity(intent);
                            } else if (position == 7) {

                                Intent intent = new Intent(getActivity(), HomeSelectSmallLastActivity.class);
                                getActivity().startActivity(intent);
                            } else {
                                Intent intent = new Intent(getActivity(), HomeSelectSmallNormalActivity.class);
                                Bundle bundle = new Bundle();
                                bundle.putString("id1", id);
                                intent.putExtras(bundle);
                                getActivity().startActivity(intent);
                            }
                        }
                    });

                    recyclerViewSmall.setAdapter(adapter_small);

                    break;






                case 3:

                    if (offset == 0) {
                        //下拉
                        listRecyview.clear();
                        listRecyview.addAll(tempListRecyview);
                        homeBigAdapter = new HomeBigAdapter(getActivity(), listRecyview);
                        recyclerView.setAdapter(homeBigAdapter);
                        headerView.stopRefresh();

//                        recyclerView.setLoadMoreState(true);

                    } else {
                        //上拉
                        listRecyview.addAll(tempListRecyview);
                        homeBigAdapter.notifyDataSetChanged();
                        footerView.stopLoad();
                    }
                    tempListRecyview.clear();
                    break;
                case 4:
                    headerView.stopRefresh();
                    footerView.stopLoad();
                    Toast.makeText(getActivity(), "请求失败了，请稍后再试~", Toast.LENGTH_SHORT).show();
                    break;

                case 5:
                    //最后一页
                    footerView.stopLoad();

//                    recyclerView.setLoadMoreState(false);
                    Toast.makeText(getActivity(), "已经是最后一页了~", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };


    @Override
    public void onResume() {
        super.onResume();
        rollPagerView.startImageCycle();
    }

    @Override
    public void onPause() {
        super.onPause();
        rollPagerView.pushImageCycle();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        rollPagerView.pushImageCycle();
    }

    @Override
    public void onRefresh(BaseHeaderView baseHeaderView) {
        offset = 0;
        initData();
    }

    @Override
    public void onLoad(BaseFooterView baseFooterView) {
        //请求网络获取下一页数据
        offset += 20;
        initData();
    }
}
